package top.wshape1.shiziapi.gateway.utils;

import com.alibaba.fastjson2.JSON;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;
import top.wshape1.shiziapi.common.utils.R;

/**
 * @author Wshape1
 * @version 1.0
 * @description
 * @since 2023-08-24
 */

public class ResponseUtil {

    public static Mono<Void> writeResponseWith403(ServerHttpResponse response, R<?> r) {
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return writeResponse(response, r);
    }

    public static Mono<Void> writeResponseWith401(ServerHttpResponse response, R<?> r) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return writeResponse(response, r);
    }

    public static Mono<Void> writeResponse(ServerHttpResponse response, R<?> r) {
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
        DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONBytes(r));
        return response.writeWith(Mono.just(dataBuffer));
    }

}
